/**
 * Program  : BootVideoTask.java
 * Author   : long
 * Create   : 2016年4月23日 下午12:39:27
 *
 * Copyright 2016 by Embedded Internet Solutions Inc.,
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Embedded Internet Solutions Inc.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with Embedded Internet Solutions Inc.
 *
 */
	
package cn.broadin.app.hotel.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


import com.alibaba.fastjson.JSONObject;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import cn.broadin.app.hotel.HomeActivity;
import cn.broadin.app.hotel.MainActivity;
import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.util.XHttpProxy;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XUtils;

/**
 * 开机视频检测
 * 
 * @author   long
 * @version  1.0.0
 * @date 2016年4月23日下午12:39:27
 */
@SuppressLint("SdCardPath")
public class IndexADTask implements Runnable{
	
	
	private String indexVideourl = "";   //动态获取开机视频广告地址
	
//	private String saveDirPath = Environment.getExternalStorageDirectory().getPath();
	private String saveDirPath = "";
	private static final String READ_ME = "indexVideo.lock";
	private static final String BOOT_VIDEO_NAME = "indexVideo.mp4";
	
	public IndexADTask(){
		
	}
	
	
	public IndexADTask(String saveDirPath,String indexVideourl){
		this.saveDirPath = saveDirPath;
		this.indexVideourl = indexVideourl;

	}
	

	/**
	 * @see java.lang.Runnable#run()
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年4月23日 下午12:39:45
	*/
	@Override
	public void run() {
		try{
			
			connectAdvServer();
		
		} catch(Exception e){
			
			e.printStackTrace();
		}
		
	}
	
	private void connectAdvServer() throws Exception{
		XLog.d("boot video save path : " + saveDirPath);
		File saveDir = new File(saveDirPath);
		if(!saveDir.exists()) {  //先判断目录是否存在，不存在，先创建目录
			saveDir.mkdirs();
		}
			
		// 判断文件是否存在
		//File bootVideoFile = new File(saveDir, BOOT_VIDEO_NAME);
		
		XLog.d("boot video request startVideoUrl = " + indexVideourl);
		
		if(indexVideourl == null || indexVideourl.equals("")) {
            indexVideourl = AppConfig.StartVideoUrl;
		}
		
		
		String downloadUrl = indexVideourl;
		
		if(TextUtils.isEmpty(downloadUrl)){
			XLog.d("boot video request server data error!");
			return;
		}
		// url 做一致hash
		String fileName = XUtils.md5(downloadUrl) + XUtils.getExtensionName(downloadUrl);
		XLog.d("boot video save filename : " + fileName);
		
		if(checkFileIsNeedUpdate(saveDir, downloadUrl, fileName)){
			//File tempFile = new File(saveDir, fileName);
			if(deleteFile()) {
				downloadFile.start();
				//downloadFile(downloadUrl, tempFile);
			}
			
			// 修改文件名称
			//tempFile.renameTo(new File(saveDir, BOOT_VIDEO_NAME));
			// 更新配置文件
			//updateReadMeFile(saveDir, downloadUrl);
		}
		
	}
	
	
	
	private Boolean deleteFile() {
		Boolean Flag = true;
		File f = new File(saveDirPath);
		File[] fl = f.listFiles();
	
		for (int i=0; i<fl.length; i++) {
			if(fl[i].toString().endsWith(".mp4") || fl[i].toString().endsWith(".MP4") || fl[i].toString().endsWith(".lock") || fl[i].toString().endsWith(".LOCK"))  
            {  
                if(fl[i].delete())  
                {  
                   Flag = true; 
                }else{  
                   Flag = false;
                }  
            } 
		}
		return Flag;
	}
	
	/**
	 * 更新配置文件
	 * 
	 * @author   long
	 * @param saveDir
	 * @param fileName
	 * @throws Exception
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年4月27日 上午10:22:29
	 */
	private void updateReadMeFile(File saveDir, String fileName) throws Exception{
		File readMeFile = new File(saveDir, READ_ME);
		if(!readMeFile.exists()){
			readMeFile.createNewFile();
		}
		String message = fileName;
		FileOutputStream fileOutputStream = new FileOutputStream(readMeFile);
		fileOutputStream.write(message.getBytes());
		fileOutputStream.flush();
		fileOutputStream.close();
	}
	
	/**
	 * 判断本地文件是否需要更新
	 * 
	 * @author   long
	 * @return
	 * @return boolean
	 * @throws Exception 
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年4月23日 下午12:59:53
	 */
	public boolean checkFileIsNeedUpdate(File saveDir, String downloadUrl, String fileName) throws Exception{
		File readMeFile = new File(saveDir, READ_ME);
		if(!readMeFile.exists()){
			readMeFile.createNewFile();
		}
		FileInputStream fin = new FileInputStream(readMeFile);   
        int length = fin.available();   
        byte [] buffer = new byte[length];   
        fin.read(buffer);       
        String content = new String(buffer, "UTF-8");   
        fin.close(); 
		if(TextUtils.isEmpty(content)){
			return true;
		}
		return !content.equals(downloadUrl);
	}
	
	/**
	 * 下载文件
	 * 
	 * @author   long
	 * @param downloadUrl
	 * @param saveFileName
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年4月23日 下午12:59:25
	 */
	Thread downloadFile = new Thread(new Runnable(){

		@Override
		public void run() {
			// TODO 自动生成的方法存根
			File downSaveDir = new File(saveDirPath);
			String downloadUrl = indexVideourl;
			String downfileName = XUtils.md5(downloadUrl) + XUtils.getExtensionName(downloadUrl);
			File tempFile = new File(downSaveDir, downfileName);
			try {
				URL url = new URL(downloadUrl);
				URLConnection con = url.openConnection();
				int contentLength = con.getContentLength();
				XLog.d("fileSize :"+contentLength);
				InputStream is = con.getInputStream();
				byte[] bs = new byte[1024];
				int len;
				OutputStream os = new FileOutputStream(tempFile);
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.close();
				is.close();
				
				mHandler.sendEmptyMessageDelayed(DOWN_SUCCESS, 5000);
				//mHandler.sendEmptyMessage(DOWN_SUCCESS);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	});
	
	
	private static final int DOWN_SUCCESS = 0; // 下载成功
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
				case DOWN_SUCCESS:
				File downSaveDir = new File(saveDirPath);
				String downloadUrl = indexVideourl;
				String downfileName = XUtils.md5(downloadUrl) + XUtils.getExtensionName(downloadUrl);
				File tempFile = new File(downSaveDir, downfileName);
				
				// 修改文件名称
				tempFile.renameTo(new File(downSaveDir, BOOT_VIDEO_NAME));
				// 更新配置文件
				try {
					updateReadMeFile(downSaveDir, downloadUrl);
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			
			super.handleMessage(msg);
		}
		
	};
	
	/*private void downloadFile(String downloadUrl, File saveFile){
		try {
			URL url = new URL(downloadUrl);
			URLConnection con = url.openConnection();
			int contentLength = con.getContentLength();
			XLog.d("fileSize :"+contentLength);
			InputStream is = con.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			OutputStream os = new FileOutputStream(saveFile);
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/

}
